#!/bin/bash

TEST_DIR=$(dirname "$0")
TEST_SRC_DIR=$(dirname "$0")/src
TEST_BIN_DIR=$(dirname "$0")/bin

export ASAN_OPTIONS
ASAN_OPTIONS+=':protect_shadow_gap=0'
ASAN_OPTIONS+=':detect_container_overflow=0'

HEADER_CHARS=80

tests_cpp=$(find "${TEST_SRC_DIR}" -type f -name '*.cpp')
failed_tests=""

for test_cpp in ${tests_cpp}; do
    test="${test_cpp/${TEST_SRC_DIR}/${TEST_BIN_DIR}}"
    test="${test/\.cpp/}"

    # Test output header
    test_name="${test_cpp/${TEST_SRC_DIR}\//}"
    chars=$(echo "${test_name}" | wc -c)
    linechars=$((${HEADER_CHARS} - ${chars} - 6))
	  line=$(printf '%*s' ${linechars} | tr ' ' '-')
	  echo -e "\n---[ ${test_name} ]${line}"

    "${test}"

    # Check for test failures
    if [ $? -ne 0 ]; then
        case "${test}" in
            # TODO: Find out why these tests are failing in CI
            *lang/mode/metal|*lang/mode/cuda|*lang/mode/opencl)
            ;;
            *)
                failed_tests+="  - ${test}\n";;
        esac
    fi

    # Test output footer
	  printf '%*s\n' ${HEADER_CHARS} | tr ' ' '='
done

if [[ "${failed_tests}" != "" ]]; then
    echo -e "\n\nFailed tests:"
    echo -e "${failed_tests}"
    exit 1
fi
